<?php

namespace App\Console\Commands\model;

use App\Dep\ModelDep;
use App\Dep\SystemDep;
use App\Dep\TrainLogDep;
use App\Enum\CommonEnum;
use App\Enum\TrainEnum;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class CheckTrainCmd extends Command
{
    //打标
    public $signature = 'model:check-train';

    public function handle()
    {
        $dep = new ModelDep();
        $logDep = new TrainLogDep();
        $systemDep = new SystemDep();

        $resTrainIng = $dep->getTrainIng();
        if ($resTrainIng->isEmpty()) {
            $this->log('no train ing model');
            return false;
        }
        $resSystem = $systemDep->first();

        $client = new Client();
        $response = $client->request('get', $resSystem->tag_domain . '/api/tasks');

        $body = $response->getBody();
        $res = json_decode($body, true);
        if(!isset($res['status']) || $res['status']!='success'){
            $this->log('server error',$res);
            return false;
        }
        $this->log('request server', $res);
        $taskData = $res['data']['tasks'];

        $resTrainIng->each(function($item) use ($taskData,$dep,$logDep,$resSystem){
            foreach ($taskData as $task){
                if($task['id'] == $item['train_num'] && $task['status'] == 'FINISHED'){
                    $modelPath = "{$resSystem->train_dir}\\{$item['name']}\\{$item['name']}.safetensors";
                    $this->log("model path {$modelPath}");
                    if(!file_exists($modelPath)){
                        $this->log('model file not exist',['id' => $item['id']]);
                        return true;
                    }
                    $distPath = "{$resSystem->model_dir}\\{$item['name']}.safetensors";
                    $this->log('copy model',['origin'=>$modelPath,'dest'=>$distPath]);
                    copy($modelPath,$distPath);

                    $data = [
                        'status' => TrainEnum::TRAIN_STATUS_TRAIN_OK,
                        'train_ok_at' => date('Y-m-d H:i:s')
                    ];
                    $dep->edit($item['id'],$data);

                    $logData = [
                        'content' => '训练完成',
                        'model_id' => $item['id'],
                    ];
                    $logDep->add($logData);
                    $this->log('train ok',['id' => $item['id']]);
                }
            }
        });

    }

    private function checkOk($sourceArr)
    {
        foreach ($sourceArr as $source) {
            if (!isset($source['origin_tag'])) {
                return false;
            }
        }
        return true;
    }

    private function log($msg, $context = [])
    {
        $this->info("do-train log: {$msg} " . json_encode($context,JSON_UNESCAPED_UNICODE));
        log_daily("check-train")->info($msg, $context);
    }


}
